using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using RideMe.Core.Properties;

namespace RideMe.Core
{
    public class RubyProcess : ProcessBase 
    {
        public event EventHandler<CheckSyntaxEventArgs> SyntaxCheckComplete;

        protected virtual void OnSytaxCheckComplete(CheckSyntaxEventArgs e)
        {
            if (SyntaxCheckComplete != null)
            {
                SyntaxCheckComplete(this, e);
            }
        }

        private bool _successful;
        private bool _fromCheckSyntax;

        /// <summary>
        /// Executes an arbitrary Ruby command. 
        /// </summary>
        /// <param name="arguments"></param>
        public override void RunCommand(string arguments, bool redirectStandardError)
        {
            ProcessExecutor processExecutor = this.CreateCommand();

            processExecutor.ExecuteCommand(Options.Instance.RubyPath + Resources.RubyExePath, arguments, redirectStandardError);
        }

        public void CheckSyntax(string pathToRubyFile)
        {
            _fromCheckSyntax = true;

            if (Validator.ValidFile(pathToRubyFile))
            {
                RunCommand(string.Format("{0} {1}", Resources.CheckSytaxArgs, pathToRubyFile), true);
            }
        }

        protected override void OnOutputReceived(DataReceivedEventArgs e)
        {
            base.OnOutputReceived(e);
            if (_fromCheckSyntax)
            {
                // This is a little odd, but this event only fires
                // if the syntax check worked. No output is received otherwise.
                _successful = true;
                OnSytaxCheckComplete(new CheckSyntaxEventArgs(e.Data));
            }
        }

        protected override void OnCompleted(EventArgs e)
        {
            base.OnCompleted(e);

            // _successful only gets set to true if it passed.
            if ((_fromCheckSyntax) && (!_successful))
            {
                OnSytaxCheckComplete(new CheckSyntaxEventArgs("FAIL"));
            }
        }

    }
}
